package com.logistics.service.impl;




import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.logistics.compont.QueryPageParam;
import com.logistics.compont.ResponseApi;
import com.logistics.mapper.OrderinfoMapper;
import com.logistics.pojo.Employee;
import com.logistics.pojo.Orderinfo;
import com.logistics.pojo.Store;
import com.logistics.service.OrderinfoService;
import com.logistics.service.feign.EmployeeFeign;
import com.logistics.service.feign.StoreFeign;
import com.logistics.util.DateUtils;
import com.logistics.util.OrderExcelUtil;
import com.logistics.util.OrderUtil;
import org.apache.commons.collections4.MapUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 服务实现层
 * @author Administrator
 *
 */
@Service
public class OrderinfoServiceImpl extends ServiceImpl<OrderinfoMapper, Orderinfo> implements OrderinfoService {

    @Autowired
    private OrderinfoMapper orderinfoMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    @Autowired
    private StoreFeign storeFeign;

    @Autowired
    private EmployeeFeign employeeFeign;

    @Override
    public Page findPage(QueryPageParam queryPageParam) {

        //mybatisplus page util
        Page page = new Page(queryPageParam.getCurrentNum(),queryPageParam.getPageSize());

        //获取条件参数
        HashMap<String,String> conditionMap = queryPageParam.getHashMap();

        //mybatisplus条件参数
        QueryWrapper<Orderinfo> queryWrapper = new QueryWrapper<>();

        //获取订单状态
        String state = conditionMap.get("state");
        if(!ObjectUtils.isEmpty(state)){
            queryWrapper.eq("state",state);
        }

        //获取订单开始时间
        String startTime = conditionMap.get("startTime");
        //获取订单结束时间
        String endTime = conditionMap.get("endTime");
        if(!ObjectUtils.isEmpty(startTime) && !ObjectUtils.isEmpty(endTime)){
            queryWrapper.between("createtime",startTime,endTime);
        }

        //订单编号
        String onum = conditionMap.get("onum");
        if(!ObjectUtils.isEmpty(onum)){
            queryWrapper.eq("onum",onum);
        }

        return orderinfoMapper.selectPage(page, queryWrapper);

    }

    @Override
    public void updateState(Map<String, Object> paramMap) {
        try {
            String onum = MapUtils.getString(paramMap,"onum");
            String state = MapUtils.getString(paramMap,"state");

            //update 更新 where 条件
            QueryWrapper<Orderinfo> queryWrapper = new QueryWrapper<Orderinfo>();
            queryWrapper.eq("onum",onum);

            //update更新的数据
            Orderinfo orderinfo = new Orderinfo();
            orderinfo.setState(Integer.valueOf(state));

            orderinfoMapper.update(orderinfo,queryWrapper);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void updateOrder(Orderinfo orderinfo) {

        //条件拼接
        QueryWrapper<Orderinfo> queryWrapper = new QueryWrapper<Orderinfo>();
        queryWrapper.eq("onum",orderinfo.getOnum());
        orderinfoMapper.update(orderinfo,queryWrapper);

    }

    @Override
    public void del(String onum) {
        QueryWrapper<Orderinfo> queryWrapper = new QueryWrapper<Orderinfo>();
        queryWrapper.eq("onum",onum);
        orderinfoMapper.delete(queryWrapper);
    }

    @Override
    public void batchUpdateState(List<String> onumIds, String state) {
        try {

            //update 更新 where 条件
            QueryWrapper<Orderinfo> queryWrapper = new QueryWrapper<Orderinfo>();
            queryWrapper.in("onum",onumIds);

            //update更新的数据
            Orderinfo orderinfo = new Orderinfo();
            orderinfo.setState(Integer.valueOf(state));

            orderinfoMapper.update(orderinfo,queryWrapper);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Orderinfo findOrderByOnum(String onum) {
        //update 更新 where 条件
        QueryWrapper<Orderinfo> queryWrapper = new QueryWrapper<Orderinfo>();
        queryWrapper.eq("onum",onum);

        return orderinfoMapper.selectOne(queryWrapper);
    }

    @Override
    public void exportExcel(List<String> onumIds) {
        //1、根据用户选择的订单编号查询对应的数据
        QueryWrapper<Orderinfo> queryWrapper = new QueryWrapper<Orderinfo>();
        queryWrapper.in("onum",onumIds);
        //要导出的数据
        List<Orderinfo> orderinfos = orderinfoMapper.selectList(queryWrapper);

        //2、调用导出工具类 导出excel
        OrderExcelUtil oeu = new OrderExcelUtil();
        try {
            oeu.exportExcel(request,response,"orderExport",orderinfos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void importData(List<Orderinfo> orderinfoList) {

        orderinfoList.forEach(orderinfo -> {
            QueryWrapper<Orderinfo> queryWrapper = new QueryWrapper<Orderinfo>()
                    .eq("onum",orderinfo.getOnum());
            Integer flag = orderinfoMapper.selectCount(queryWrapper);

            //1、数据 在表存在 修改
            if(1 == flag){
                orderinfoMapper.update(orderinfo,queryWrapper);
            //2、导入的数据在表 不存在 新增
            }else{
                orderinfo.setOnum(OrderUtil.genOrderNum());
                orderinfoMapper.insert(orderinfo);
            }
        });

    }

    @Override
    public Map<String, Map<String, Integer>> statisitcsOrder() {
        // 门店           日期      数量
        Map<String, Map<String, Integer>> resultMap = new LinkedHashMap<String, Map<String, Integer>>();

        //1、统计门店
        ResponseApi<List<LinkedHashMap<String,Integer>>> stores = storeFeign.queryAllStores();
        //2、对应门店员工列表
        List<LinkedHashMap<String,Integer>> storeList = stores.getData();

        //3、门店名称map
        Map<Integer,String> storeMap = new HashMap<Integer, String>();

        //3.1 拼接sid 1,2,3,
        StringBuffer sids = new StringBuffer();
        storeList.forEach(linkedHashMap -> {
            Integer sid_val1 = linkedHashMap.get("sid");
            //将门店名称存起来 为最终返回对象准备
            storeMap.put(sid_val1,linkedHashMap.get("sname")+"");

            sids.append(sid_val1+",");
        });

        //去掉最后一位 ，1,2,3
        String sidToStr = sids.toString().substring(0,sids.toString().lastIndexOf(","));
        //查询各个门店对应的员工列表
        ResponseApi<Map<Integer, List<Employee>>> empBySidRes = employeeFeign.findEmpBySid(sidToStr);
        //门店sid 员工列表
        Map<Integer, List<Employee>> empBySidResMap = empBySidRes.getData();

        //遍历门店 empList 存的员工对象
        empBySidResMap.forEach((sid,empList) -> {
            //装配 结果 1月-3
            // 日期      数量
            Map<String, Integer> dateMap = new LinkedHashMap<>();

            //第1门店
            //Map<门店id,List<员工>>
            List<Integer> eids = new ArrayList<Integer>();

            //遍历门店对应的员工 将员工id 存入eids
            empList.forEach(emp -> {
                eids.add(emp.getEid());
            });

            //如果门店有员工
            if(eids.size()>0){
                //根据门店员工列表进行查询
                List<Orderinfo> orderinfoList = orderinfoMapper.selOrderListByEmpIds(eids);

                //根据时间过滤订单 2023-1-18  2023-1-29
                orderinfoList.forEach(orderinfo -> {
                    //将创建时间 格式为yyyy-MM-dd
                    String createTime = DateUtils.formatDateToStr(orderinfo.getCreatetime(), "yyyy-MM-dd");
                    //取创建时间的月份 MM
                    String month = createTime.substring(createTime.indexOf("-")+1, createTime.lastIndexOf("-"));//01
                    //MM 为 11 取 对应 返回值的key 11月
                    String monthKey = getMonthKey(month);//1月
                    //11月对应数据
                    Integer orderNum = dateMap.get(monthKey);//1月,1
                    //如果有值 则累加 没有值 则初始化
                    try {
                        if(orderNum>0){
                            orderNum+=1;
                        }else{
                            orderNum=1;
                        }
                        dateMap.put(monthKey,orderNum);
                    } catch (NullPointerException e) {
                        orderNum=1;
                        dateMap.put(monthKey,orderNum);
                    }

                    resultMap.put(storeMap.get(sid),dateMap);

//                long createTimestr = orderinfo.getCreatetime().getTime();
//                //获取本年度 12个月
//                Map<String, String> startDayAndEndDayByMonthInYear = DateUtils.getStartDayAndEndDayByMonthInYear();
//                startDayAndEndDayByMonthInYear.forEach((startTime,endTime) -> {
//
//                    //返回值Map key
//                    String month = startTime.substring(startTime.indexOf("-")+1, startTime.lastIndexOf("-"));
//                    String monthKey = getMonthKey(month);//1月
//
//                    //月份开始时间戳
//                    long startTimestr = DateUtils.formatDate2(startTime).getTime();
//                    //月份结束时间戳
//                    long endTimestr = DateUtils.formatDate2(endTime).getTime();
//
//                    if(createTimestr>=startTimestr && createTimestr<=endTimestr){
//                        dateMap.put(monthKey,1);
//                    }
//                });

                });
            }

        });

        return resultMap;
    }

    public void clearDateMap(Map<String,Integer> dateMap){
        dateMap.put("1月",0);
        dateMap.put("2月",0);
        dateMap.put("3月",0);
        dateMap.put("4月",0);
        dateMap.put("5月",0);
        dateMap.put("6月",0);
        dateMap.put("7月",0);
        dateMap.put("8月",0);
        dateMap.put("9月",0);
        dateMap.put("10月",0);
        dateMap.put("11月",0);
        dateMap.put("12月",0);
    }

    /**
     * 01 1月
     * @param month
     * @return
     */
    public String getMonthKey(String month){
        Map<String,String> monthMap = new LinkedHashMap<String,String>();
        monthMap.put("01","1月");
        monthMap.put("02","2月");
        monthMap.put("03","3月");
        monthMap.put("04","4月");
        monthMap.put("05","5月");
        monthMap.put("06","6月");
        monthMap.put("07","7月");
        monthMap.put("08","8月");
        monthMap.put("09","9月");
        monthMap.put("10","10月");
        monthMap.put("11","11月");
        monthMap.put("12","12月");

        return monthMap.get(month);
    }


}
